from django.shortcuts import render,HttpResponse
from .models import Passage, Tag
# Create your views here.


def index(request):
    contents = Passage.objects.all().order_by('-time')[:5]
    tags = Tag.objects.all().order_by('tagName')
    return render(request,"index.html", {'contents': contents, 'tags': tags})


def passages(request):
    passage_id = request.GET.get("pid", default=None)

    if passage_id is not None and passage_id.isdigit() == True:
        tags = Tag.objects.all().order_by('tagName')
        pags = Passage.objects.filter(id=passage_id)
        contents = Passage.objects.all().order_by('-time')[:5]
        return render(request, 'passages.html', {'contents': contents, 'pags': pags, 'tags': tags})
    else:
        contents = Passage.objects.all().order_by('-time')[:5]
        tags = Tag.objects.all().order_by('tagName')
        return render(request, 'passages.html', {'contents': contents, 'pags': contents, 'tags': tags})

def tags(request):
    tag_name = request.GET.get("tag", default=None)
    tags = Tag.objects.all().order_by('tagName')
    contents = Passage.objects.all().order_by('-time')[:5]
    if tag_name is not None:
        tag = Tag.objects.filter(tagName=tag_name)
        if len(tag) == 1:
            pags = tag[0].passage_set.all().order_by('-time')[:5]
            return render(request, 'passages.html', {'contents': contents, 'pags': pags, 'tags': tags})
    return render(request, 'tags.html', {'contents': contents, 'tags': tags})

def focus(request):
    contents = Passage.objects.all().order_by('-time')[:5]
    tags = Tag.objects.all().order_by('tagName')
    return render(request, "focus.html", {'contents': contents, 'tags': tags})